package cn.bigcontainer.d2m;

import java.io.File;
import java.io.FileInputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bigcontainer.common.exception.BCException;
import cn.bigcontainer.common.util.BCUtil;
import cn.bigcontainer.d2m.util.D2MConstant;

public class Doc2MarkDown {

	private static Logger LOG = LoggerFactory.getLogger(Doc2MarkDown.class);
	//

	public static XWPFDocument getDocument(String file) {
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			return new XWPFDocument(inputStream);
		} catch (Exception e) {
			LOG.error(D2MConstant.ERR_DOC.getMessage(), e);
			throw new BCException(e, D2MConstant.ERR_DOC);
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		String importPath = "C:/work/tmp/test.docx";
		File f = new File(importPath);
		// 当前目录
		String cd = f.getParent();
		String fileName = f.getName();

		// markdown文档目录
		String mdDir = cd + "/" + FilenameUtils.getBaseName(fileName) + ".md";
		BCUtil.mkdirs(mdDir);
		// markdown图片目录
		String picDirName = "pic";
		String picDir = mdDir + "/" + picDirName;
		BCUtil.mkdirs(picDir);
		LOG.info("{},{}", mdDir, picDir);
		XWPFDocument doc = getDocument(importPath);
		// 打开输出流，写入
		BCUtil.writeToFile(mdDir + "/" + FilenameUtils.getBaseName(fileName) + ".md", (out) -> {
			// 标题级别集合，如标题级别编号为：1.1.1.，则集合为：[1,1,1]
			List<Integer> titleLevels = new ArrayList<Integer>();
			// 图片的索引
			Integer picIndex = 0;
			// 遍历段落，生成md
			for (IBodyElement e : doc.getBodyElements()) {
				if (e.getElementType() == BodyElementType.TABLE) {
					XWPFTable table = (XWPFTable)e;
					LOG.info("table-{}", table.getNumberOfRows());
//					| 11   | 12   | 13   |      |
//					| ---- | ---- | ---- | ---- |
//					| 21   | 22   | 23   |      |
//					| 31   | 32   | 33   |      |
//					|      |      |      |      |
					for (int i = 0; i < table.getNumberOfRows(); i ++) {
						out.write("| ");
						XWPFTableRow r = table.getRow(i);
						for (int j = 0; j < r.getTableCells().size(); j ++) {
							XWPFTableCell c = r.getCell(j);
							out.write(c.getText());
							out.write(" |");
						}
						out.write("\r\n");
						if (i == 0) {
							out.write("| ");
							for (int j = 0; j < r.getTableCells().size(); j ++) {
								out.write("----");
								out.write(" |");
							}
							out.write("\r\n");
						} else if (i == (table.getNumberOfRows() - 1)) {
							out.write("| ");
							for (int j = 0; j < r.getTableCells().size(); j ++) {
								out.write("    ");
								out.write(" |");
							}
							out.write("\r\n");
						}
					}
				} else if (e.getElementType() == BodyElementType.PARAGRAPH) {
					XWPFParagraph paragraph = (XWPFParagraph) e;
					LOG.info("getStyle-{},getParagraphText-{}", paragraph.getStyle(), paragraph.getParagraphText());
					// 1.生成标题编号，例如：1.1.1.
					// 获取标题级别
					Integer level = BCUtil.parseInt(paragraph.getStyle(), 0) - 2;
					if (level >= 0) {
						if (titleLevels.size() >= (level + 1)) {
							int levelSize = titleLevels.size();
							// 最后一位的值加1
							titleLevels.set(level, titleLevels.get(level) + 1);
							// 删除titleLevels中level位置以后的数据
							for (int i = 0; i < (levelSize - level - 1); i++) {
								titleLevels.remove(levelSize - i - 1);
							}
						} else {
							titleLevels.add(1);
						}
						for (int i = 0; i <= level; i++) {
							out.write("#");
						}
						out.write(" ");
						for (Integer l : titleLevels) {
							out.write(l.toString());
							out.write(".");
						}
					}
					// 2.段落正文
					out.write(paragraph.getParagraphText());
					// 3.段落中的图片，仅支持图片为单独段落的情况
					for (XWPFRun r : paragraph.getRuns()) {
						for (XWPFPicture p : r.getEmbeddedPictures()) {
							// 保存图片到picDir目录
							String picFileName = ++picIndex + "."
									+ FilenameUtils.getExtension(p.getPictureData().getFileName());
							String picFile = picDir + "/" + picFileName;
							FileUtils.writeByteArrayToFile(new File(picFile), p.getPictureData().getData());
							// ![${picFileName}](./${picDirName}/${picFileName})
							out.write("![");
							out.write(picFileName);
							out.write("](./");
							out.write(picDirName);
							out.write("/");
							out.write(picFileName);
							out.write(")");
							LOG.info("生成图片：" + picFileName);
						}
					}
					out.write("\r\n");
				}
			}
		});

	}

}
